package com.atguigu.controller;

import com.atguigu.entity.Role;
import com.atguigu.service.PermissionService;
import com.atguigu.service.RolePermissionService;
import com.atguigu.service.RoleService;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController extends BaseController{

    @DubboReference
    private RoleService roleService;
    @DubboReference
    private PermissionService permissionService;
    @DubboReference
    private RolePermissionService rolePermissionService;

    @RequestMapping
    @PreAuthorize("hasAuthority('role.show')")
    public String getAll(Map map, HttpServletRequest request) {
        Map<String, Object> filters = getFilters(request);
        PageInfo<Role> page = roleService.findPage(filters);
        map.put("page", page);
        map.put("filters", filters);
        return "role/index";
    }


    @RequestMapping("/create")
    @PreAuthorize("hasAuthority('role.create')")
    public String create() {
        return "role/create";
    }
    @RequestMapping("/save")
    @PreAuthorize("hasAuthority('role.create')")
    public String insert(Role role) {
        roleService.insert(role);
        return "common/success";
    }

    @RequestMapping("/edit/{id}")
    @PreAuthorize("hasAuthority('role.edit')")
    public String edit(@PathVariable Long id, Map map) {
        Role role = roleService.getById(id);
        map.put("role", role);
        return "role/edit";
    }

    @RequestMapping("/update")
    @PreAuthorize("hasAuthority('role.edit')")
    public String update(Role role) {
        roleService.update(role);
        return "common/success";
    }

    @RequestMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('role.delete')")
    public String delete(@PathVariable Long id) {
        roleService.delete(id);
        return "redirect:/role";
    }

    @RequestMapping("/assignShow/{roleId}")
    @PreAuthorize("hasAuthority('role.assign')")
    public String assignShow(@PathVariable Long roleId,Map map){
        map.put("roleId", roleId);
        List<Map<String, Object>> zNodes = permissionService.findZnodes(roleId);
        map.put("zNodes", zNodes);
        return "role/assignShow";
    }
    @RequestMapping("/assignPermission")
    @PreAuthorize("hasAuthority('role.assign')")
    public String assignRole(Long roleId,String[] permissionIds) {
        rolePermissionService.insertRolePermission(roleId,permissionIds);
        return "common/success";
    }


}
